/*
 * Copyright (c) 2018-2999 深圳市阿毛科技有限公司 All rights reserved.
 *
 * https://www.lamyz.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.lam.mall.api.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alipay.api.internal.util.AlipaySignature;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.service.WxPayService;
import com.lam.common.pay.config.AlipayConfig;
import com.lam.common.utils.ServletUtils;
import com.lam.common.utils.StringUtils;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.mall.enums.PayType;
import com.lam.mall.service.PayService;


/**
 * @author lam
 */
@RestController
@RequestMapping("/notify/pay")
public class PayNoticeApiController {
	
	 private final Logger logger = LoggerFactory.getLogger(getClass());
	
    /**
     * 小程序支付
     */
	@Autowired
    private WxPayService wxMiniPayService;
	@Autowired
    private PayService payService;

	@Log(oper = "微信支付回调通知", businessType = BusinessType.UPDATE)
    @RequestMapping("/wxPay")
    public void wxOk(@RequestBody String xmlData) {
    	
        try {
			WxPayOrderNotifyResult parseOrderNotifyResult = wxMiniPayService.parseOrderNotifyResult(xmlData);
			String payNo = parseOrderNotifyResult.getOutTradeNo();
			String bizPayNo = parseOrderNotifyResult.getTransactionId();

			// 根据内部订单号更新order settlement
			payService.queryPayResult(payNo, bizPayNo, PayType.WXPAY.code());

			HttpServletResponse response = ServletUtils.getResponse();
			response.getWriter().print("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
		} catch (Exception e) {
			logger.error("微信支付回调通知异常", e);
			ServletUtils.outWrite("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[通知异常]]></return_msg></xml>");
		}
    }
    
    @Log(oper = "支付宝支付回调通知", businessType = BusinessType.UPDATE)
    @RequestMapping("/alipay")
    public void alipayOk(HttpServletRequest request, HttpServletResponse response) {

		try {
			// 获取支付宝POST过来反馈信息
			Map<String, Object> params = ServletUtils.getParamter(request);
			Map<String, String> strParams = new HashMap<>();
			params.entrySet().stream().forEach(t->strParams.put(t.getKey(), StringUtils.toString(t.getValue())));
			// 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
			// 计算得出通知验证结果
			boolean verifyResult = AlipaySignature.rsaCheckV1(strParams, AlipayConfig.me().getAlipayPublicKey(), 
					AlipayConfig.me().getCharset(), AlipayConfig.me().getSignType());
			if (verifyResult) {// 验证成功
				// 商户订单号
				String payNo = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
				// 支付宝交易号
				String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
				// 交易状态
				String tradeStatus = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
				if (StringUtils.equalsAny(tradeStatus, "TRADE_FINISHED", "TRADE_SUCCESS")) {
					//交易完成，不可退款, //支付成功，可以退款
					payService.queryPayResult(payNo, trade_no, PayType.ALIPAY.code());
				} 
				response.getWriter().print("success");
			} else {// 验证失败
				response.getWriter().print("fail");
			}
		} catch (Exception e) {
			logger.error("支付宝支付回调通知异常", e);
			ServletUtils.outWrite("fail");
		}
    }
}
